package cn.edu.scnu.springbootcinema.controller;

import cn.edu.scnu.springbootcinema.entity.User;
import cn.edu.scnu.springbootcinema.entity.UserFavorite;
import cn.edu.scnu.springbootcinema.service.UserFavoriteService;
import cn.edu.scnu.springbootcinema.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserFavoriteService userFavoriteService;

    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String email,
                           @RequestParam String password,
                           @RequestParam String confirmPassword,
                           RedirectAttributes redirectAttributes) {
        // 输入验证
        if (username == null || username.isEmpty() || email == null || email.isEmpty() ||
                password == null || password.isEmpty() || confirmPassword == null || confirmPassword.isEmpty()) {
            redirectAttributes.addAttribute("error", "所有字段不能为空");
            return "redirect:/register";
        }

        // 验证 email 格式
        if (!isValidEmail(email)) {
            redirectAttributes.addAttribute("error", "邮箱格式不正确");
            return "redirect:/register";
        }

        // 检查用户是否已经注册
        if (userService.getById(email) != null) {
            redirectAttributes.addAttribute("error", "邮箱已注册");
            return "redirect:/register";
        }

        // 验证密码匹配
        if (!password.equals(confirmPassword)) {
            redirectAttributes.addAttribute("error", "密码不匹配");
            return "redirect:/register";
        }

        try {
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            user.setPassword(password); // 加密密码

            if (userService.register(user)) {
                redirectAttributes.addAttribute("success", "注册成功");
                return "redirect:/login";
            } else {
                redirectAttributes.addAttribute("error", "注册失败，请稍后再试");
                return "redirect:/register";
            }
        } catch (Exception e) {
            // 记录日志
            redirectAttributes.addAttribute("error", "注册失败，请稍后再试");
            return "redirect:/register";
        }
    }

    // 验证 email 格式
    private boolean isValidEmail(String email) {
        String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
        return email.matches(emailRegex);
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String email,
                        @RequestParam String password,
                        HttpSession session, Model model) {
        User user = userService.login(email, password);
        if (user != null) {
            session.setAttribute("user", user);
            session.setAttribute("userFavorites", userFavoriteService.getFavoriteMovieIdsByUserId(user.getUserId()));
            return "redirect:/index";
        } else {
            model.addAttribute("error", "账号或密码错误");
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index";
    }

    @GetMapping("/reset")
    public String resetPage() {
        return "reset";
    }

    @PostMapping("/reset")
    public String reset(@RequestParam String email, @RequestParam String password) {
        User user = userService.getById(email);
        if (user == null) {
            return "redirect:/reset?error=用户不存在";
        }
        user.setPassword(password);
        userService.updateById(user);
        return "redirect:/login";
    }

    @GetMapping("/check-email")
    @ResponseBody
    public boolean checkEmail(@RequestParam String email) {
        User user = userService.getById(email);
        return user == null;
    }

    @RequestMapping("/center")
    public String center(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {

            return "usercenter";
        } else {
            return "redirect:/login";
        }
    }

    @RequestMapping("/like")
    public String like(@RequestParam Integer movieId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        System.out.println(movieId);
        if (user == null)
            return "redirect:/login";
        userService.likeMovie(user.getUserId(), movieId);
        session.setAttribute("userFavorites", userFavoriteService.getFavoriteMovieIdsByUserId(user.getUserId()));
        return "redirect:/movie/detail?id=" + movieId;
    }

    @RequestMapping("/dislike")
    public String dislike(@RequestParam Integer movieId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null)
            return "redirect:/login";
        userService.dislikeMovie(user.getUserId(), movieId);
        session.setAttribute("userFavorites", userFavoriteService.getFavoriteMovieIdsByUserId(user.getUserId()));
        return "redirect:/movie/detail?id=" + movieId;
    }

}